<!-- 我的 - 编辑个人信息 -->
<template>
  <view>
    <z-navbar title="个人信息" :border-bottom="true"></z-navbar>
    <view class="px-4 pb-10">
      <u-form-item label="头像" required prop="avatar" right-icon="arrow-right">
        <view class="flex justify-end items-center">
          <button class="u-reset-button w-54 h-54 rounded-full mr-0" open-type="chooseAvatar"
            @chooseavatar="onAvatarChoose">
            <image v-if="formData.avatar" class="w-54 h-54 rounded-full" :src="formData.avatar" />
            <view v-else class="w-54 h-54 bg-#999 rounded-full"></view>
          </button>
        </view>
      </u-form-item>
      <u-form :model="formData" ref="form" :label-style="labelStyle" label-width="180" :error-type="state.errorType">
        <u-form-item :label='state.isAdviser ? "姓名" : "昵称"' required prop="nickname">
          <u-input v-model="formData.nickname" type="nickname" input-align="right" :placeholder-style="placeholderStyle"
            :custom-style="inputStyle" :placeholder="formRules.nickname[0].message" />
        </u-form-item>
        <u-form-item label="ID号">
          <u-input v-model="state.detailData.userId" input-align="right" disabled :placeholder-style="placeholderStyle"
            :custom-style="inputStyle" />
        </u-form-item>
        <u-form-item v-if="state.isAdviser" label="公司">
          <u-input v-model="formData.company_name" input-align="right" :placeholder-style="placeholderStyle"
            :custom-style="inputStyle" placeholder="输入您所在企业全称" />
        </u-form-item>
        <u-form-item v-if="state.isAdviser" label="职位" required prop="position">
          <u-input v-model="formData.position" input-align="right" :placeholder-style="placeholderStyle"
            :custom-style="inputStyle" :placeholder="formRules.position[0].message" />
        </u-form-item>
        <u-form-item v-if="state.isAdviser" label="常驻地区" required prop="region" right-icon="arrow-right">
          <u-input v-model="formData.region" input-align="right" disabled :placeholder-style="placeholderStyle"
            :custom-style="pickerStyle" :placeholder="formRules.region[0].message"
            @click="state.showRegionPicker = true" />
          <!-- 地区选择 -->
          <z-region-picker :show="state.showRegionPicker" title="选择常驻地区" @close="state.showRegionPicker = false"
            @confirm="onRegionConfirm" />
        </u-form-item>
        <u-form-item v-if="state.isAdviser" label="擅长领域" required prop="expertiseList" right-icon="arrow-right">
          <u-input :modelValue="expertiseName" input-align="right" disabled :placeholder-style="placeholderStyle"
            :custom-style="pickerStyle" placeholder="请选择擅长领域" @click="state.showFieldPicker = true" />
          <field-select-picker :show="state.showFieldPicker" :data="formData.expertiseList"
            @close="state.showFieldPicker = false" @confirm="onFieldConfirm" />
        </u-form-item>
        <u-form-item v-if="state.isAdviser" label="课程主题" required prop="course_theme">
          <u-input v-model="formData.course_theme" input-align="right" :placeholder-style="placeholderStyle"
            :custom-style="inputStyle" :placeholder="formRules.course_theme[0].message" />
        </u-form-item>
        <view class="flex min-h-260 pt-3">
          <view class="flex-shrink-0 mt-1 ml--2 w-196">
            <view class="c-#333 text-28 font-bold label-left"><text class="pt-0.75 c-#FF513A">*</text>{{ state.isAdviser ?
              '自我介绍' : '个人简介' }}</view>
          </view>
          <view class="flex-1 flex justify-end relative">
            <u-input v-model="formData.self_desc" input-align="right" :maxlength="state.isAdviser ? 500 : 100" type="textarea" style="width: 100%;"
              height="180" :auto-height="true" :placeholder-style="placeholderStyle" :custom-style="textAreaStyle"
              placeholder="干练又丰富的个人简介更受欢迎哦~" />
          </view>
        </view>
        <view class="flex justify-end mb-3 z-2 c-#999 text-24">{{ enteredNum }}/{{ state.isAdviser ? 500 : 100 }}</view>
        <u-line color="#F5F5F5" :hair-line="false" />
        <view class="flex h-200">
          <view class="flex-shrink-0 c-#333 text-28 mt-3 font-bold label-left">背景图
          </view>
          <view class="flex-1 flex items-center justify-end">
            <z-file-upload ref="backUploader" :fileList="backImages" width="252" height="144" maxCount="1" />
          </view>
        </view>
        <view v-if="state.isAdviser" class="flex h-200">
          <view class="flex-shrink-0">
            <view class="c-#333 text-28 mt-3 font-bold label-left"><text class="c-#FF513A">*</text>BANNER图</view>
            <view class="mt-1 c-#F4AF22 text-24">尺寸为700*400</view>
          </view>
          <view class="flex-1 flex items-center justify-end">
            <z-file-upload ref="bannerUploader" :fileList="bannerImages" width="252" height="144" maxCount="1" />
          </view>
        </view>
        <u-line color="#F5F5F5" :hair-line="false" />
      </u-form>
      <view class="btn-submit mt-2" @click="onSubmit">保存</view>

    </view>
    <!-- <view class="bottom-wrap-16 bg-white"> -->



  </view>
</template>

<script setup>
import { showToast, showModal, navigate } from "@/common/util/uni";
import { refreshPrePage } from '@/common/util/util'
import { uploadUrl } from '@/common/config/config'
import { useUserStore } from '@/store/user'
import { getUserHomepage, postUserProfile } from '@/common/http/module/center.js'
import { getExpertiseList } from '@/common/http/module/common'

const userStore = useUserStore()
const state = reactive({
  detailData: '', // 简介数据
  isAdviser: false, // 是否为顾问
  showRegionPicker: false,
  showFieldPicker: false,
  errorType: ['toast'],
  fieldList: [],
  isAdviser: false
})

const formData = reactive({
  avatar: '',
  nickname: '',
  company_name: '',
  position: '',
  region: '',
  province: '',
  city: '',
  area: '',
  expertiseList: [],
  self_desc: '',
  course_theme: '',
  banner: '',
  background_image: ''
})

const formRules = {
  nickname: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }],
  position: [{ required: true, message: '输入您职位', trigger: ['blur', 'change'] }],
  course_theme: [{ required: true, message: '输入您擅长的课程主题', trigger: ['blur', 'change'] }],
  region: [{ required: true, message: '请选择常驻地区', trigger: ['blur', 'change'] }],
}

// 表单label样式
const placeholderStyle = "fontSize: '28rpx', color: '#999'"
const labelStyle = {
  fontFamily: 'PingFang SC',
  color: '#333333',
  fontSize: '28rpx',
  fontWeight: 'bold'
}
const inputStyle = {
  color: '#333',
  fontSize: '28rpx',
  paddingRight: '38rpx'
}
const pickerStyle = {
  color: '#333',
  fontSize: '28rpx',
}

const textAreaStyle = {
  color: '#333',
  fontSize: '28rpx',
  paddingBottom: '0rpx'
}



// 头像上传
function onAvatarChoose(e) {
  const url = e.detail.avatarUrl
  uni.uploadFile({
    url: uploadUrl,
    header: { token: userStore.token },
    filePath: url,
    name: 'file',
    success: res => {
      const data = JSON.parse(res.data)
      if (data.code != 1) {
        showToast('上传失败')
      }
      formData.avatar = data.data.fullurl
    },
    fail: () => {
      showToast('上传失败')
    }
  })
}

const form = ref()
const bannerUploader = ref()

const bannerImages = ref([])

const backUploader = ref()

const backImages = ref([])

const enteredNum = computed(() => formData.self_desc ? formData.self_desc.length : 0)
const expertiseName = computed(() => {
  if (!formData.expertiseList || formData.expertiseList.length == 0) return ''
  return formData.expertiseList.map(item => item.expertise_name).join(',')
})

// 加载个人信息
async function loadData() {
  // state.isAdviser = option.isAdviser

  const { data } = await getUserHomepage(state.user_id)
  state.detailData = data
  // 是否为顾问
  state.isAdviser = data && data.identity == 1
  backFillFormData()
  getExpertiseList().then(res => {
    state.fieldList = res.data?.map(item => {
      return {
        label: item.expertise_name,
        value: item.id
      }
    })
    console.log('getExpertiseList', state.fieldList);
  })
}

function backFillFormData() {
  if (!state.detailData) return
  formData.avatar = state.detailData.avatar
  formData.nickname = state.detailData.nickname
  formData.company_name = state.detailData.intro?.company_name
  formData.position = state.detailData.intro?.position
  formData.self_desc = state.isAdviser ? state.detailData.intro?.self_desc : state.detailData.introduce
  formData.course_theme = state.detailData.intro?.course_theme
  formData.banner = state.detailData.intro?.banner
  formData.background_image = state.detailData.background_image
  formData.province = state.detailData.intro?.province
  formData.city = state.detailData.intro?.city
  formData.area = state.detailData.intro?.area
  formData.region = state.detailData.intro?.address
  formData.expertiseList = state.detailData.intro?.expertise_ids.split(',').map((item, index) => {
    return {
      id: item,
      expertise_name: state.detailData.intro?.expertise[index]
    }
  })
  bannerImages.value = state.detailData.intro?.banner.map(item => {
    return { url: item }
  })
  backImages.value = state.detailData.background_image ? [{ url: state.detailData.background_image }] : []
}

// 地区选择
function onRegionConfirm(e) {
  console.log('onRegionConfirm', e);
  const { province, city, area } = e
  formData.province = province.id
  formData.city = city.id
  formData.area = area?.id
  formData.region = province.name + city.name + area?.name
}

// 领域选择
function onFieldConfirm(e) {
  formData.expertiseList = e
}

function onSubmit() {
  form.value.validate(valid => {
    if (!valid) return
    if (state.isAdviser && formData.expertiseList.length == 0) {
      showToast('请选择擅长领域', 'none')
      return
    }
    if (state.isAdviser && !bannerUploader.value.isAllUploaded()) return
    // if (!backUploader.value.isAllUploaded()) return

    const bannerImageList = state.isAdviser ? bannerUploader.value.getUploadedList() : []
    if (state.isAdviser && bannerImageList.length == 0) {
      showToast('请先上传BANNER图', 'none')
      return
    }
    const backImageList = backUploader.value.isAllUploaded() ? backUploader.value?.getUploadedList() : []
    // if (backImageList.length == 0) {
    //   showToast('请先上传背景图', 'none')
    //   return
    // }


    let params = {}
    if (state.isAdviser) {
      params = {
        ...formData,
        expertise_ids: formData.expertiseList.map(item => item.id).join(','),
        banner: bannerImageList[0].serverUrl,
        background_image: backImageList.length!=0 ? backImageList[0].serverUrl : '',
      }
    } else {
      params = {
        avatar: formData.avatar,
        nickname: formData.nickname,
        introduce: formData.self_desc,
        background_image: backImageList.length!=0 ? backImageList[0].serverUrl : '',
      }
    }
    if (formData.nickname.length > 10) {
      showToast('昵称不能超过十个字', 'none')
      return
    }
    // const adviserParams = {
    //   ...formData,
    //   expertise_ids: formData.expertiseList.map(item => item.id).join(','),
    //   banner: bannerImageList[0].serverUrl,
    // }

    // const commonParams = {
    //   avatar: formData.avatar,
    //   nickname: formData.nickname,
    //   introduce: formData.self_desc
    // }
    // const params = state.isAdviser ? adviserParams : commonParams
    console.log('onSubmit', params);
    postUserProfile(params).then(() => {
      showToast('已保存')
      refreshPrePage('loadData', 1)
      userStore.loadUserInfo()
      setTimeout(() => uni.navigateBack(), 600)
    })
  })
}

onLoad((options) => {
  state.isAdviser = options.isAdviser
  loadData()
})

onReady(() => {
  nextTick(() => form.value.setRules(formRules))
})
</script>

<style lang="scss" scoped>
.option-item {
  display: flex;
  align-items: center;
  color: #333;
  font-size: 28rpx;
  font-family: PingFangSC-Medium;
}
</style>
